/**
 * 将旧系统的排期数据同步到新系统
 */

import * as path from "path";
import * as fs from "fs";
import * as os from "os";

import dayjs from "dayjs";

import { getDeviceInfoByCode, materialPage, planPage, planSave } from "./api/newApi";
import { getPlanDetail, getPlanList, getProgramMaterial } from "./api/oldApi";
import { calcMaterialData } from "./util";

const __dirname = path.resolve();
const DIR_PATH = path.resolve(__dirname, "./downloadPlans");
const MATERIALS_FILE_NAME = path.resolve(DIR_PATH, "./materialsFileName");
const DEVICE_CODE = path.resolve(DIR_PATH, "./deviceCode");
const RELEVANCE_INFO = path.resolve(DIR_PATH, "./relevanceInfo");
const SKIP_PLAN_NAME_PATH = path.resolve(DIR_PATH, "./skipPlanName");

// 只同步包含该机构名称的数据
const INCLUDES_OFFICE = ["广州"];

let currentPlan: any = null;

(async () => {
	try {
		main();
	} catch (err) {
		console.log("err: ", err instanceof Error ? err.message : err);
	}
})();

async function main() {
	try {
		if (!fs.existsSync(DIR_PATH)) fs.mkdirSync(DIR_PATH);
		if (!fs.existsSync(RELEVANCE_INFO)) fs.mkdirSync(RELEVANCE_INFO);

		const allPlans = await getPlanList().then((res) => res.data.data);
		if (allPlans.length === 0) {
			console.log("排期全部迁移完毕");
			process.exit(1);
		}

		for (let i = 0; i < allPlans.length; i++) {
			currentPlan = allPlans[i];

			if (!INCLUDES_OFFICE.includes(currentPlan.officeName)) {
				console.log(`跳过【${currentPlan.name}】`);
				return;
			}

			if (fs.existsSync(SKIP_PLAN_NAME_PATH)) {
				const content = await fs.promises.readFile(SKIP_PLAN_NAME_PATH);
				const skipFileName = content.toString()?.split(os.EOL)?.filter(Boolean);

				if (skipFileName.includes(currentPlan.name)) {
					console.log(`跳过【${currentPlan.name}】`);
					continue;
				}
			}

			const remarks = dayjs().format("YYYY-MM-DD HH:mm:ss") + " 迁移上传";

			const linkMaterials: any = [];
			const linkDevices: any = [];

			const { devices, programs } = await getPlanDetail(currentPlan.id).then((res) => res.data || {});

			if (!programs) {
				console.log(`【${currentPlan.name}】排期没有节目单数据`);
				return;
			}

			if (!devices) {
				console.log(`【${currentPlan.name}】排期没有设备数据`);
				return;
			}

			if (programs.length === 0) {
				console.log(`【${currentPlan.name}】排期没有节目单数据`);
			}

			if (devices.length === 0) {
				console.log(`【${currentPlan.name}】排期没有设备数据`);
			}

			// 收集节目单中的素材
			for (let j = 0; j < programs.length; j++) {
				const program = programs[j];

				const materials = await getProgramMaterial(program.id).then((res) => res.data?.data || []);
				if (materials.length === 0) {
					console.log(`【${program.name}】节目单数据没有素材数据`);
				}

				for (let k = 0; k < materials.length; k++) {
					const material = materials[k];
					const resList = await materialPage(material.fileName).then((res) => res.data?.data?.records || []);
					if (resList && resList[0]) {
						// linkMaterials.push(resList[0]);

						// TODO 待测试
						const idx = linkMaterials.findIndex((e: any) => material.fileName === resList[0].fileName);
						if (idx === -1) {
							linkMaterials.push(resList[0]);
						} else {
							console.log(`【${material.name}】素材已经存在【${currentPlan.name}】排期中`);
						}
					} else {
						console.log(`没有找到【${material.name}】对应的素材数据`);
						// 记录失败的继续上传
						fs.appendFileSync(MATERIALS_FILE_NAME, `${material.fileName}${os.EOL}`);
					}
				}
			}

			// 收集设备
			for (let j = 0; j < devices.length; j++) {
				const { no } = devices[j];
				const device = await getDeviceInfoByCode(no).then((res) => res.data?.data || null);
				if (device) {
					// linkDevices.push(device);

					// TODO 待测试
					const idx = linkDevices.findIndex((e: any) => device.code === no);
					if (idx === -1) {
						linkDevices.push(device);
					} else {
						console.log(`【${device.code}】设备已经存在【${currentPlan.name}】排期中`);
					}
				} else {
					console.log(`编号为【${no}】没有找到对应的设备数据`);
					fs.appendFileSync(DEVICE_CODE, `${currentPlan.name}-${no}${os.EOL}`);
				}
			}

			// 先查询有没有重复的
			const planList = await planPage(currentPlan.name).then((res) => res.data?.data?.records || []);
			let savePlan: any = null;
			if (planList.length === 0) {
				// 提交排期
				const playWeeks = currentPlan.playWeeks.replace("7", "0");
				await planSave({
					status: "0",
					startDate: `${currentPlan.startDate} 00:00:00`,
					officeName: currentPlan.officeName,
					officeCode: currentPlan.officeId,
					createUser: "超级管理员",
					createUserName: "超级管理员",
					playWeeks,
					// startTime: planMap.currentPlan.startTime,
					startTime: "08:00", // 固定每天 08:00
					playFrequency: "1", // 1 每天, 3 星期
					name: currentPlan.name,
					endDate: `${currentPlan.stopDate} 00:00:00`,
					remarks,
					// 关联都置空
					devices: [],
					materials: []
				});
				console.log(`【${currentPlan.name}】排期新增成功`);

				// 重新获取排期数据
				const resList = await planPage(currentPlan.name).then((res) => res.data?.data?.records || []);
				savePlan = resList[0];
			} else {
				// console.log(`【${currentPlan.name}】排期数据已存在, 更新操作`);
				savePlan = planList[0];
			}

			const saveData = {
				...savePlan,
				remarks,
				// officeName: currentPlan.officeName,
				// officeCode: currentPlan.officeId,
				devices: linkDevices,
				materials: calcMaterialData(linkMaterials, currentPlan.startDate, currentPlan.startTime)
			};
			await planSave(saveData);
			console.log(`【${saveData.name}】排期更新成功`);

			const relevanceFilePath = path.resolve(RELEVANCE_INFO, `${savePlan.code}-${savePlan.name}.json`);
			await fs.promises.writeFile(relevanceFilePath, JSON.stringify(saveData, null, 2));
		}
		console.log("success");
	} catch (err) {
		console.log("排期迁移失败: ", err instanceof Error ? err.message : err);

		// 记录失败的继续上传
		fs.appendFileSync(SKIP_PLAN_NAME_PATH, `${currentPlan.name}${os.EOL}`);
		console.log("========== 继续迁移 ==========");
		main();
	}
}
